package homevideo_model

import (
	"fmt"
	"iptv_server/v3/src/database"

	"gorm.io/gorm"
)

type Detail struct {
	// gorm.Model
	ID uint `gorm:"primarykey" json:"-"`
	// id         uint `gorm:"primaryKey"`
	VodId      string `json:"vod_id"` // == ID 或 SubId非空时 ==/others/SubId/ID
	CategoryID uint   `gorm:"index" json:"-"`
	DoubanID   string `gorm:"type:varchar(15);index" json:"-"`
	Name       string `json:"vod_name,omitempty"`
	Pic        string `gorm:"type:varchar(2048)" json:"vod_pic,omitempty"`

	//"Cate" : "cover",  # cover是合集. folder 是一行一行的目录模式!!!
	// 不用 vod_tag 这个了!
	IsFolder    int    `json:"cate,omitempty"` //重定向到这个cateID, categoryID
	Year        string `gorm:"type:varchar(20)" json:"vod_year,omitempty"`
	Remark      string `json:"vod_remarks,omitempty"`
	Area        string `json:"vod_area,omitempty"`
	Type        string `json:"type_name,omitempty"`
	Actors      string `json:"vod_actor,omitempty"`
	Director    string `json:"vod_director,omitempty"`
	Description string `json:"vod_content,omitempty"`
	// Plays          []Play `json:"list,omitempty"`

	Plays []Play `json:"-"`
}

// func (d *Detail) GetDetail() (ds []Play, err error) {
// 	err = database.DB.Where("detail_id = ?", d.ID).Find(&ds).Error
// 	return
// }

func GetDetail(id int) (d *Detail, err error) {
	// d = &Detail{ID: id}
	d = &Detail{}
	// err = database.DB.Joins("Plays").First(d, id).Error

	err = database.DB.Model(d).Preload("Plays", func(db *gorm.DB) *gorm.DB {
		return database.DB.Order("id ASC")
	}).First(d, id).Error

	fmt.Printf("d.Plays: len=%v\n", len(d.Plays))
	// err = database.DB.Model(cat).Preload("Details", func(db *gorm.DB) *gorm.DB {
	// 	return database.DB.Limit(limit).Offset(offset)
	// }).Find(cat).Error

	// // err = database.DB.First(d, id).Error

	// // ASC DESC
	// err = database.DB.Table("details").
	// 	Select("details.*,plays.*").
	// 	Joins("left join plays on details.id = plays.detail_id").
	// 	Where("details.id = ?", id).
	// 	Order("plays.id ASC").Scan(d).Error
	if err == nil && len(d.VodId) == 0 {
		d.VodId = fmt.Sprintf("%d", d.ID)
	}

	return
}

func (d *Detail) Count() (count *int64, err error) {
	// database.DB.Raw("select count(*) from details  where category_id = ?",)
	count = new(int64)
	err = database.DB.Model(d).Where("category_id = ?", d.CategoryID).Count(count).Error
	return
}

func (d *Detail) Create() error {
	return database.DB.Create(d).Error
}

func (d *Detail) Save() error {
	return database.DB.Save(d).Error
}

// func UpdateDetail(db *gorm.DB, id uint, url string, playerArgs string) error {
// 	p := &Play{
// 		url:        url,
// 		playerArgs: playerArgs,
// 	}
// 	p.ID = id
// 	r := db.Save(p)
// 	return r.Error
// }
